package com.mynews.activities.search;

import android.annotation.SuppressLint;
import android.app.Application;
import android.widget.SearchView;

import androidx.annotation.NonNull;
import androidx.databinding.BindingAdapter;
import androidx.lifecycle.AndroidViewModel;

import com.mynews.activities.App;
import com.mynews.activities.main.ui.recommend.RecommendVM;
import com.mynews.activities.view.PullingLayout;
import com.mynews.adapter.NewsAdapter;
import com.mynews.bean.NewsBean;
import com.mynews.databinding.ActivitySearchBinding;
import com.mynews.utils.BmobApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SearchVM extends AndroidViewModel {
    @SuppressLint("StaticFieldLeak")
    private static SearchActivity searchActivity;
    @SuppressLint("StaticFieldLeak")
    private static ActivitySearchBinding binding;
    private static final List<NewsBean> data=new ArrayList<>();
    private static final List<NewsBean> searchData=new ArrayList<>();
    private static int skip=0;
    private static int count=0;

    public SearchVM(@NonNull @NotNull Application application) {
        super(application);
    }

    public void setBinding(ActivitySearchBinding binding, SearchActivity searchActivity) {
        SearchVM.searchActivity =searchActivity;
        SearchVM.binding =binding;
        binding.setAdp(new NewsAdapter(searchActivity,data));
        refresh(null);
    }
    @BindingAdapter("bindSearchView")
    public static void bindSearchView(SearchView searchView, SearchVM searchVM){
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                data.clear();
                for (NewsBean serviceBean:searchData) {
                    if (serviceBean.title.contains(newText)){
                        data.add(serviceBean);
                    }
                }
                searchActivity.runOnUiThread(() -> binding.getAdp().notifyDataSetChanged());
                return false;
            }
        });
    }
    private static void refresh(PullingLayout pullingLayout) {
        if (skip==0) {
            data.clear();
            searchData.clear();
        }
        BmobApi.get( "https://api2.bmob.cn/1/classes/news?order=-createdAt&limit=50&skip="+skip,new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo = ja.getJSONObject(i);
                        data.add(new NewsBean(jo.getString("objectId"),jo.getString("title"),jo.getString("content"),jo.getString("ownerId"),jo.getString("updatedAt"),jo.getString("type"),null));
                        searchData.add(new NewsBean(jo.getString("objectId"),jo.getString("title"),jo.getString("content"),jo.getString("ownerId"),jo.getString("updatedAt"),jo.getString("type"),null));
                    }
                    searchActivity.runOnUiThread(()->{
                        binding.getAdp().notifyDataSetChanged();
                        if (pullingLayout!=null){
                            if (response.request().url().queryParameter("skip").equals("0")){
                                pullingLayout.refreshFinish(0);
                            }else{
                                pullingLayout.loadmoreFinish(0);
                            }
                        }
                        count=data.size();
                    });
                }catch (JSONException e) {e.printStackTrace();}
            }
        });
    }
    @BindingAdapter("bindPull")
    public static void bindPull(PullingLayout pullingLayout, SearchVM searchVM){
        pullingLayout.setPullDownEnabled(true);
        pullingLayout.setPullUpEnabled(true);
        pullingLayout.setOnRefreshListener(pullToRefreshLayout -> {
            skip=0;
            refresh(pullToRefreshLayout);
        });
        pullingLayout.setOnLoadMoreListener(pullToRefreshLayout -> {
            skip=count;
            refresh(pullToRefreshLayout);
        });
    }
}
